package image;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

import map.Properties;

import file.FileManipulator;

public class ImageResizer {
	
	private PixelArray pixels;
	private int targetWidth;
	private int targetHeight;
	private double scale;
	
	public ImageResizer(PixelArray pixels) {
		this.pixels = pixels;
	}
	
	public BufferedImage getTilePixels(PixelArray pixels, int tileX, int tileY, int zoom) {
		int tileSize = Properties.tileSize;
		BufferedImage tile = new BufferedImage(tileSize, tileSize, BufferedImage.TYPE_INT_RGB);
		// Tile is out of image area, painting tile white.
		if (tileX < 0 || tileY < 0) {
			Graphics g = tile.getGraphics();
			g.setColor(Color.white);
			g.fillRect(0, 0, tile.getWidth(), tile.getHeight());
			return tile;
		}
		// Height and width of image after zooming.
		this.targetHeight = (int) (Properties.mapHeight * Math.pow(2, zoom - 1));
		this.targetWidth = (int) (Properties.mapWidth * Math.pow(2, zoom - 1));
		scale = calculateScale();
		// Tile starting coordinates on image.
		int startX = tileSize * tileX;
		int startY = tileSize * tileY;
		
		int pixel = 0;
		for (int i = 0; i < tileSize; i++) {
			for (int j = 0; j < tileSize; j++) {
				pixel = calculateColor(startX + i, startY + j, pixels);
				tile.setRGB(i, j, pixel == 0 ? Color.white.getRGB() : Color.black.getRGB());
			}
		}
		return tile;
	}
	
	public int getHeight() {
		return pixels.getHeight();
	}
	
	public int getWidth() {
		return pixels.getWidth();
	}
	
	/**
	 * @return image scale.
	 */
	public double calculateScale() {
		double newScale = (double)getHeight() / (double)targetHeight;
		double widthScale = (double)getWidth() / (double)targetWidth;
		if (widthScale > newScale) {
			newScale = widthScale;
		}
		return newScale;
	}
	
	public int calculateColor(int x, int y, PixelArray pixels) {
		int x1 = (int)((double)x * scale);
		int y1 = (int)((double)y * scale);
		int x2 = (int)((double)(x + 1) * scale);
		int y2 = (int)((double)(y + 1) * scale);
		
		int color = 0;
		for (int i = x1; i <= x2; i++) {
			for (int j = y1; j <= y2; j++) {
				color = (Integer)pixels.get(i, j) == 0 ? color - 1 : color + 1;
			}
		}
		return color <= 0 ? 0 : 1;
	}
	
	public enum coordinateType {
		WIDTH, HEIGHT;
	}
}
